using System.Collections;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    [SerializeField] private GameManager gameManager;
    [SerializeField] private GameObject bulletPrefab;
    [SerializeField] private GameObject bulletAnchor;
    [SerializeField] private GameObject shield;
    [SerializeField] private Camera mainCam;
    
    private Vector3 mousePos;
    private Rigidbody playerRb;
    private float horizontalInput;
    private float verticalInput;
    private float thrust = 200.0f;

    public bool isShield = false;
    
    void Start()
    {
        playerRb = GetComponent<Rigidbody>();
    }

    void Update()
    {
        if (!gameManager.isPause)
        {
            horizontalInput = Input.GetAxis("Horizontal");
            verticalInput = Input.GetAxis("Vertical");

            mousePos = mainCam.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10.0f));
            transform.LookAt(mousePos, Vector3.back);

            // player movement
            playerRb.AddRelativeForce(Vector3.forward * (verticalInput * thrust));
            playerRb.AddRelativeForce(Vector3.right * (horizontalInput * thrust), ForceMode.Force);

            if (Input.GetKeyDown(KeyCode.Mouse0))
            {
                FireShot();
            }
        }
    }

    private void FireShot()
    {
        Vector3 relativePos = mousePos - transform.position;
        Quaternion fireRotation = Quaternion.LookRotation(relativePos, Vector3.right);
        Instantiate(bulletPrefab, bulletAnchor.transform.position, fireRotation);
    }

    public void ActivateShield()
    {
        isShield = true;
        shield.SetActive(true);
        StartCoroutine(HideShield());
    }

    IEnumerator HideShield()
    {
        yield return new WaitForSeconds(5f);
        shield.SetActive(false);
        isShield = false;
    }
}
